package cn.lizemin.fakedata.common;

import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author 李泽民
 * @Date 2024/1/18 20:07
 * @Description
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private static final ImmutableMap<Class<?>, ResultEnum> EXCEPTIONS;

    static {
        ImmutableMap.Builder<Class<?>, ResultEnum> builder = ImmutableMap.builder();
        builder.put(DataIntegrityViolationException.class, ResultEnum.SQL_ERROR);
        builder.put(BindException.class, ResultEnum.ILLEGAL_PARAM);
        EXCEPTIONS = builder.build();
    }

    @ExceptionHandler(BusinessException.class)
    public RespBean exception(BusinessException ex) {
        log.error("发生了异常：{}", ExceptionUtils.getStackTrace(ex));
        return RespBean.fail(ex.getResultEnum());
    }

    @ExceptionHandler(Exception.class)
    public RespBean exception(Exception ex) {
        log.error("发生了异常：{}", ExceptionUtils.getStackTrace(ex));
        ResultEnum res = EXCEPTIONS.get(ex.getClass());
        if (Objects.nonNull(res)) {
            return RespBean.fail(res);
        }
        return RespBean.fail().message(ex.getMessage());
    }

}
